// 这份代码专门处理逻辑层的操作
const studentDao = require('../dao/studentDao');

const powerService = require('./powerService');

const studentService = {
    /*
     * 分页获取学生列表
     */
    async getStudentList(uid, userType, pg) {
        // 用户权限认证
        let result;
        try {
            result = await powerService.checkPowerByUid(uid, '查看学生信息');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑
        let num = 5;
        let start = (pg - 1) * num;
        let func = studentDao.getStudentList;
        // 进一步控制辅导员和院长的权限（暂不设计，院长表还没建立）
        // 修复方法，辅导员表要添加辅导员属于哪个院系，然后根据院系来查询
        // 修复方法，院长表 要添加院长属于哪个院系，然后根据院系来查询
        try {
            let studentList = await func(start, num);
            result = { success: true, msg: "查询成功", studentList: studentList }
        } catch (error) {
            result = { success: false, msg: "查询数据库时出错，查询失败" }
        }
        return result;
    },
    // /*
    //  * 获取所有学生列表 - 不分页
    //  */
    // async getStudentList(uid, userType) {
    //     // 用户权限认证
    //     let result;
    //     try {
    //         result = await powerService.checkPowerByUid(uid, '查看学生信息');
    //         if (result == false) {
    //             return {success: false, msg: "权限不足，无法操作"};
    //         }
    //     } catch (err) {
    //         return {success: false, msg: "操作过程中出错"};
    //     }
    //     // 真正的执行逻辑
    //     let func = studentDao.getStudentList;
    //     // 进一步控制辅导员和院长的权限（暂不设计，院长表还没建立）
    //     // 修复方法，辅导员表要添加辅导员属于哪个院系，然后根据院系来查询
    //     // 修复方法，院长表 要添加院长属于哪个院系，然后根据院系来查询
    //     try {
    //         let studentList = await func();
    //         result = { success: true, msg: "查询成功", studentList: studentList }
    //     } catch (error) {
    //         result = { success: false, msg: "查询数据库时出错，查询失败" }
    //     }
    //     return result;
    // },
    /*
     * 获取学生详细信息
     */
    async getStudentInfo(uid, userType, studentID) {
        let result;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '查看学生信息');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑（后续需要专门限制 辅导员 院长 的查询范围）
        try {
            let studentInfo = await studentDao.getStudentInfo(studentID);
            if (studentInfo.length == 0) {
                result = { success: false, msg: "查询为空" }
            } else {
                result = { success: true, msg: "查询成功", studentInfo: studentInfo }
            }
        } catch (error) {
            result = { success: false, msg: "查询数据库时出错，查询失败" }
        }
        return result;
    },
    /*
     * 获取所有学生列表接口
     */
    async getAllStudentList(uid, userType) {
        let result;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '查看学生信息');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑（后续需要专门限制 辅导员 院长 的查询范围）
        let funcMap = {
            "辅导员": studentDao.getAllStudentListOfFaculty,
            "学院书记": studentDao.getAllStudentListOfFaculty
        };
        let func = funcMap[userType];
        if (func == undefined) func = studentDao.getAllStudentList;
        try {
            let studentList = await func(uid);
            if (studentList.length == 0) {
                result = { success: false, msg: "查询为空" }
            } else {
                result = { success: true, msg: "查询成功", studentList: studentList }
            }
        } catch (error) {
            result = { success: false, msg: "查询数据库时出错，查询失败" }
        }
        return result;
    },
    /*
     * 获取所有学生列表接口 - 限制200条数据
     */
    async getAllStudentListLimit(uid, userType) {
        let result;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '查看学生信息');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑（后续需要专门限制 辅导员 院长 的查询范围）
        let funcMap = {
            "辅导员": studentDao.getAllStudentListOfFacultyLimit,
            "学院书记": studentDao.getAllStudentListOfFacultyLimit
        };
        let func = funcMap[userType];
        if (func == undefined) func = studentDao.getAllStudentListLimit;
        try {
            let studentList = await func(uid);
            if (studentList.length == 0) {
                result = { success: false, msg: "查询为空" }
            } else {
                result = { success: true, msg: "查询成功", studentList: studentList }
            }
        } catch (error) {
            result = { success: false, msg: "查询数据库时出错，查询失败" }
        }
        return result;
    },
    /*
     * 搜索学生列表接口
     */
    async searchStudentListLimit(uid, userType, name, cardId, className, facultyId, tname, warningLevelId) {
        let result;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '查看学生信息');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑（后续需要专门限制 辅导员 院长 的查询范围）
        let funcMap = {
            "辅导员": studentDao.searchStudentListOfFacultyLimit,
            "学院书记": studentDao.searchStudentListOfFacultyLimit
        };
        let func = funcMap[userType];
        if (func == undefined) func = studentDao.searchStudentListLimit;
        try {
            let studentList = await func(uid, name, cardId, className, facultyId, tname, warningLevelId);
            if (studentList.length == 0) {
                result = { success: false, msg: "查询为空" }
            } else {
                result = { success: true, msg: "查询成功", studentList: studentList }
            }
        } catch (error) {
            result = { success: false, msg: "查询数据库时出错，查询失败" }
        }
        return result;
    },
    /*
     * 新增学生信息接口
     */
    async addStudentInfo(uid, userType, data) {
        let result;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '修改学生基本信息');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑
        try {
            let tmp = await studentDao.findStudentIdByCardId(data.cardId);
            if (tmp.length) {
                result = { success: false, msg: `已经存在学号为${data.cardId}的学生` }
                return result;
            }
            let updateResult = await studentDao.addStudentInfo(data);
            if (updateResult.insertId == 0) {
                result = { success: false, msg: "新增失败" }
            } else {
                result = { success: true, msg: "新增成功" }
            }
        } catch (error) {
            result = { success: false, msg: "操作数据库时出错，修改失败" }
        }
        return result;
    },
    /*
     * 修改学生信息接口
     */
    async updateStudentInfo(uid, userType, data) {
        let result;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '修改学生基本信息');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑
        try {
            let updateResult = await studentDao.updateStudentInfo(data);
            if (updateResult.affectedRows == 0) {
                result = { success: false, msg: "修改失败" }
            } else {
                result = { success: true, msg: "修改成功" }
            }
        } catch (error) {
            result = { success: false, msg: "修改数据库时出错，修改失败" }
        }
        return result;
    },
    /*
     * 修改学生预警级别的接口
     */
    async updateStudentWarningLevel(uid, userType, data) {
        let result;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '修改预警级别');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑
        try {
            let updateResult = await studentDao.updateStudentWarningLevel(data);
            if (updateResult.affectedRows == 0) {
                result = { success: false, msg: "修改失败" }
            } else {
                result = { success: true, msg: "修改成功" }
            }
        } catch (error) {
            result = { success: false, msg: "修改数据库时出错，修改失败" }
        }
        return result;
    },
    /*
     * 使用学生的姓名和学号查询到学生的id
     */
    async findStudentIdByNameAndCardId(cardId, name) {
        // 辅助接口不需要权限认证
        let result;
        try {
            let findrResult = await studentDao.findStudentIdByNameAndCardId(cardId, name);
            if (findrResult.length == 0) {
                result = { success: false, msg: "查询为空" }
            } else {
                result = { success: true, msg: "查询成功", studentId: findrResult[0].studentId }
            }
        } catch (error) {
            result = { success: false, msg: "查看数据库时出错，查看失败" }
        }
        return result;
    },
    /*
     * 获取所有班级的接口
     */
    async getAllClassList() {
        let result;
        try {
            result = await studentDao.getAllClassList();
            result = { success: true, msg: "查询成功", allClassList: result };
        } catch (error) {
            result = { success: false, msg: "查看数据库时出错，查看失败" };
        }
        return result;
    },
    /*
     * 获取所有学院的接口
     */
    async getAllFacultys() {
        let result;
        try {
            result = await studentDao.getAllFacultys();
            result = { success: true, msg: "查询成功", allFacultys: result };
        } catch (error) {
            result = { success: false, msg: "查看数据库时出错，查看失败" };
        }
        return result;
    },
    /*
     * 获取所有预警级别的接口
     */
    async getAllWarningLevelList() {
        let result;
        try {
            result = await studentDao.getAllWarningLevelList();
            result = { success: true, msg: "查询成功", levels: result };
        } catch (error) {
            result = { success: false, msg: "查看数据库时出错，查看失败" };
        }
        return result;
    },
    /*
     * 导出学生信息接口
     */
    async exportStudentInfo(uid, userType, studentIdList) {
        let result;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '导出学生信息');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑
        try {
            console.log('【导出学生信息 开始访问数据库的时间】', Date.now());
            let tmpResult = await studentDao.exportStudentInfo(studentIdList);
            console.log('【导出学生信息 数据库访问完毕的时间】', Date.now());
            let addResId = [];
            result = [];
            for (let i = 0; i < tmpResult.length; i++) {
                if (!(addResId.includes(tmpResult[i].studentId))) {
                    result.push(tmpResult[i]);
                    addResId.push(tmpResult[i].studentId);
                }
            }
            result = { success: true, msg: "导出成功", result };
        } catch (error) {
            result = { success: false, msg: "查询数据库时出错，导出失败" };
        }
        return result;
    }
};

module.exports = studentService;